/*
 * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy
 * of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 *
 */

package com.zhou.common.quartz.test.example5.miss_fire_policy;

import static org.quartz.DateBuilder.nextGivenSecondDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SchedulerMetaData;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.calendar.AnnualCalendar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Properties;

/**
 * Demonstrates the behavior of <code>StatefulJob</code>s, as well as how misfire instructions affect the firings of
 * triggers of <code>StatefulJob</code> s - when the jobs take longer to execute that the frequency of the trigger's
 * repitition.
 * 演示<code>StatefulJob<code>s的行为，以及错误指令如何影响
 * <code>StatefulJob<code>s触发器的触发——当作业的执行时间超过触发器重复的频率时。
 * <p>
 * While the example is running, you should note that there are two triggers with identical schedules, firing identical
 * jobs. The triggers "want" to fire every 3 seconds, but the jobs take 10 seconds to execute. Therefore, by the time
 * the jobs complete their execution, the triggers have already "misfired" (unless the scheduler's "misfire threshold"
 * has been set to more than 7 seconds). You should see that one of the jobs has its misfire instruction set to
 * <code>SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT</code>, which causes it to fire
 * immediately, when the misfire is detected. The other trigger uses the default "smart policy" misfire instruction,
 * which causes the trigger to advance to its next fire time (skipping those that it has missed) - so that it does not
 * refire immediately, but rather at the next scheduled time.
 * 在运行示例时，您应该注意到有两个具有相同调度的触发器，它们触发相同的作业。触发器“希望”每3秒触发一次，
 * 但作业需要10秒才能执行。因此，当作业完成执行时，触发器已经“失效”了(除非调度器的“失效阈值”设置为7秒以上)。
 * 您应该看到其中一个作业的misfire指令集为<code>SimpleTrigger。
 * MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT<code>，当检测到失火时，它会立即触发。
 * 另一个触发器使用默认的“智能策略”失火指令，
 * 这将导致触发器提前到下一个触发时间(跳过那些它错过的)——这样它就不会立即重新触发，而是在下一个预定的时间重新触发。
 * </p>
 * 执行失败，打不着火
 * <p>
 * miss fire 的具体文档说明
 * https://nurkiewicz.com/2012/04/quartz-scheduler-misfire-instructions.html
 */
public class MisfireExample {

  public static void main(String[] args) throws Exception {

    MisfireExample example = new MisfireExample();
    example.run();
  }

  public void run() throws Exception {
    Logger log = LoggerFactory.getLogger(MisfireExample.class);

    log.info("------- Initializing -------------------");

    //设置丢失触发的时间为5s
    Properties properties = new Properties();
    properties.setProperty("org.quartz.jobStore.misfireThreshold", "5000");
    properties.setProperty("org.quartz.threadPool.threadCount", "25");
    // First we must get a reference to a scheduler
    SchedulerFactory sf = new StdSchedulerFactory(properties);
    Scheduler sched = sf.getScheduler();

    log.info("------- Initialization Complete -----------");

    log.info("------- Scheduling Jobs -----------");

    // jobs can be scheduled before start() has been called

    AnnualCalendar holidays = new AnnualCalendar();
    sched.addCalendar("holidays", holidays, false, false);
    // 在未来的几秒钟内获得“漂亮的一轮”时间....
    Date startTime = nextGivenSecondDate(null, 15);

    //statfuljob1将每3秒运行一次(但它每次执行耗时10秒)
    JobDetail job = newJob(StatefulDumbJob.class).withIdentity("statefulJob1", "group1")
            .usingJobData(StatefulDumbJob.EXECUTION_DELAY, 10000L).build();

    SimpleTrigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(startTime)
            .withSchedule(simpleSchedule().withIntervalInSeconds(6).withRepeatCount(3)
                    //直接丢弃，在下一个时间触发，如果可执行次数都没有了，trigger会置为完成状态
                    //.withMisfireHandlingInstructionNextWithRemainingCount()
                    //.withMisfireHandlingInstructionNextWithExistingCount()
                    //立即执行，剩余次数
                    //.withMisfireHandlingInstructionNowWithExistingCount()
                    //立即执行一次，并继续执行剩下的
                    //.withMisfireHandlingInstructionNowWithRemainingCount()
                    //每15秒发射一次的SimpleTrigger在发射失败5分钟后，一旦有机会发射，就会发射20次
                    //.withMisfireHandlingInstructionIgnoreMisfires()
                    //withMisfireHandlingInstructionFireNow 通常只用于非重复性的任务
                    //MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_REMAINING_REPEAT_COUNT
                    .withMisfireHandlingInstructionFireNow()
            ).build();


    Date ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every "
            + trigger.getRepeatInterval() / 1000 + " seconds");

    // statefulJob2 will run every three seconds
    // (but it will delay for ten seconds - and therefore purposely misfire after a few iterations)
    //statefulJob2将每3秒运行一次(但它每次执行耗时10秒—因此在几次迭代后故意不启动)。
    job = newJob(StatefulDumbJob.class).withIdentity("statefulJob2", "group1")
            .usingJobData(StatefulDumbJob.EXECUTION_DELAY, 10000L).build();

    trigger = newTrigger()
            .withIdentity("trigger2", "group1")
            .startAt(startTime)
            .withSchedule(simpleSchedule().withIntervalInSeconds(3).withRepeatCount(3)
                            //超时后立即触发，目前测试数量也一样
                            /*.withMisfireHandlingInstructionNowWithExistingCount()
                            .withMisfireHandlingInstructionNowWithRemainingCount()*/
//                    .withMisfireHandlingInstructionNextWithExistingCount()
                            .withMisfireHandlingInstructionIgnoreMisfires()
            ) // set misfire instructions
            .build();

    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every "
            + trigger.getRepeatInterval() / 1000 + " seconds");

    log.info("------- Starting Scheduler ----------------");

    // jobs don't start firing until start() has been called...
    sched.start();

    log.info("------- Started Scheduler -----------------");

    try {
      // sleep for ten minutes for triggers to file....
      Thread.sleep(600L * 1000L);
    } catch (Exception e) {
      //
    }

    log.info("------- Shutting Down ---------------------");

    sched.shutdown(true);

    log.info("------- Shutdown Complete -----------------");

    SchedulerMetaData metaData = sched.getMetaData();
    log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
  }

}
